4 * The parent class to generate form fields. Any field type should
5 * be a subclass of this.
7 abstract class HTMLFormField
{
10 protected $mValidationCallback;
11 protected $mFilterCallback;
14 protected $mLabel; # String label, as HTML. Set on construction.
16 protected $mClass = '';
17 protected $mVFormClass = '';
18 protected $mHelpClass = false;
20 protected $mOptions = false;
21 protected $mOptionsLabelsNotFromMessage = false;
22 protected $mHideIf = null;
25 * @var bool If true will generate an empty div element with no label
28 protected $mShowEmptyLabels = true;
36 * This function must be implemented to return the HTML to generate
37 * the input object itself. It should not implement the surrounding
38 * table cells/rows, or labels/help messages.
40 * @param string $value The value to set the input to; eg a default
41 * text for a text input.
43 * @return string Valid HTML.
45 abstract function getInputHTML( $value );
48 * Same as getInputHTML, but returns an OOUI object.
49 * Defaults to false, which getOOUI will interpret as "use the HTML version"
51 * @param string $value
52 * @return OOUI\Widget|false
54 function getInputOOUI( $value ) {
59 * True if this field type is able to display errors; false if validation errors need to be
60 * displayed in the main HTMLForm error area.
63 public function canDisplayErrors() {
68 * Get a translated interface message
70 * This is a wrapper around $this->mParent->msg() if $this->mParent is set
71 * and wfMessage() otherwise.
73 * Parameters are the same as wfMessage().
78 $args = func_get_args();
80 if ( $this->mParent
) {
81 $callback = [ $this->mParent
, 'msg' ];
83 $callback = 'wfMessage';
86 return call_user_func_array( $callback, $args );
90 * If this field has a user-visible output or not. If not,
91 * it will not be rendered
95 public function hasVisibleOutput() {
100 * Fetch a field value from $alldata for the closest field matching a given
103 * This is complex because it needs to handle array fields like the user
104 * would expect. The general algorithm is to look for $name as a sibling
105 * of $this, then a sibling of $this's parent, and so on. Keeping in mind
106 * that $name itself might be referencing an array.
108 * @param array $alldata
109 * @param string $name
112 protected function getNearestFieldByName( $alldata, $name ) {
115 while ( preg_match( '/^(.+)\[([^\]]+)\]$/', $tmp, $m ) ) {
116 array_unshift( $thisKeys, $m[2] );
119 if ( substr( $tmp, 0, 2 ) == 'wp' &&
120 !array_key_exists( $tmp, $alldata ) &&
121 array_key_exists( substr( $tmp, 2 ), $alldata )
123 // Adjust for name mangling.
124 $tmp = substr( $tmp, 2 );
126 array_unshift( $thisKeys, $tmp );
130 while ( preg_match( '/^(.+)\[([^\]]+)\]$/', $tmp, $m ) ) {
131 array_unshift( $nameKeys, $m[2] );
134 array_unshift( $nameKeys, $tmp );
137 for ( $i = count( $thisKeys ) - 1; $i >= 0; $i-- ) {
138 $keys = array_merge( array_slice( $thisKeys, 0, $i ), $nameKeys );
141 $key = array_shift( $keys );
142 if ( !is_array( $data ) ||
!array_key_exists( $key, $data ) ) {
147 $testValue = (string)$data;
155 * Helper function for isHidden to handle recursive data structures.
157 * @param array $alldata
158 * @param array $params
160 * @throws MWException
162 protected function isHiddenRecurse( array $alldata, array $params ) {
163 $origParams = $params;
164 $op = array_shift( $params );
169 foreach ( $params as $i => $p ) {
170 if ( !is_array( $p ) ) {
171 throw new MWException(
172 "Expected array, found " . gettype( $p ) . " at index $i"
175 if ( !$this->isHiddenRecurse( $alldata, $p ) ) {
182 foreach ( $params as $i => $p ) {
183 if ( !is_array( $p ) ) {
184 throw new MWException(
185 "Expected array, found " . gettype( $p ) . " at index $i"
188 if ( $this->isHiddenRecurse( $alldata, $p ) ) {
195 foreach ( $params as $i => $p ) {
196 if ( !is_array( $p ) ) {
197 throw new MWException(
198 "Expected array, found " . gettype( $p ) . " at index $i"
201 if ( !$this->isHiddenRecurse( $alldata, $p ) ) {
208 foreach ( $params as $i => $p ) {
209 if ( !is_array( $p ) ) {
210 throw new MWException(
211 "Expected array, found " . gettype( $p ) . " at index $i"
214 if ( $this->isHiddenRecurse( $alldata, $p ) ) {
221 if ( count( $params ) !== 1 ) {
222 throw new MWException( "NOT takes exactly one parameter" );
225 if ( !is_array( $p ) ) {
226 throw new MWException(
227 "Expected array, found " . gettype( $p ) . " at index 0"
230 return !$this->isHiddenRecurse( $alldata, $p );
234 if ( count( $params ) !== 2 ) {
235 throw new MWException( "$op takes exactly two parameters" );
237 list( $field, $value ) = $params;
238 if ( !is_string( $field ) ||
!is_string( $value ) ) {
239 throw new MWException( "Parameters for $op must be strings" );
241 $testValue = $this->getNearestFieldByName( $alldata, $field );
244 return ( $value === $testValue );
246 return ( $value !== $testValue );
250 throw new MWException( "Unknown operation" );
252 } catch ( Exception
$ex ) {
253 throw new MWException(
254 "Invalid hide-if specification for $this->mName: " .
255 $ex->getMessage() . " in " . var_export( $origParams, true ),
262 * Test whether this field is supposed to be hidden, based on the values of
263 * the other form fields.
266 * @param array $alldata The data collected from the form
269 function isHidden( $alldata ) {
270 if ( !$this->mHideIf
) {
274 return $this->isHiddenRecurse( $alldata, $this->mHideIf
);
278 * Override this function if the control can somehow trigger a form
279 * submission that shouldn't actually submit the HTMLForm.
282 * @param string|array $value The value the field was submitted with
283 * @param array $alldata The data collected from the form
285 * @return bool True to cancel the submission
287 function cancelSubmit( $value, $alldata ) {
292 * Override this function to add specific validation checks on the
293 * field input. Don't forget to call parent::validate() to ensure
294 * that the user-defined callback mValidationCallback is still run
296 * @param string|array $value The value the field was submitted with
297 * @param array $alldata The data collected from the form
299 * @return bool|string True on success, or String error to display, or
300 * false to fail validation without displaying an error.
302 function validate( $value, $alldata ) {
303 if ( $this->isHidden( $alldata ) ) {
307 if ( isset( $this->mParams
['required'] )
308 && $this->mParams
['required'] !== false
311 return $this->msg( 'htmlform-required' )->parse();
314 if ( isset( $this->mValidationCallback
) ) {
315 return call_user_func( $this->mValidationCallback
, $value, $alldata, $this->mParent
);
321 function filter( $value, $alldata ) {
322 if ( isset( $this->mFilterCallback
) ) {
323 $value = call_user_func( $this->mFilterCallback
, $value, $alldata, $this->mParent
);
330 * Should this field have a label, or is there no input element with the
331 * appropriate id for the label to point to?
333 * @return bool True to output a label, false to suppress
335 protected function needsLabel() {
340 * Tell the field whether to generate a separate label element if its label
345 * @param bool $show Set to false to not generate a label.
348 public function setShowEmptyLabel( $show ) {
349 $this->mShowEmptyLabels
= $show;
353 * Can we assume that the request is an attempt to submit a HTMLForm, as opposed to an attempt to
354 * just view it? This can't normally be distinguished for e.g. checkboxes.
356 * Returns true if the request has a field for a CSRF token (wpEditToken) or a form identifier
357 * (wpFormIdentifier).
359 * @param WebRequest $request
362 protected function isSubmitAttempt( WebRequest
$request ) {
363 return $request->getCheck( 'wpEditToken' ) ||
$request->getCheck( 'wpFormIdentifier' );
367 * Get the value that this input has been set to from a posted form,
368 * or the input's default value if it has not been set.
370 * @param WebRequest $request
371 * @return string The value
373 function loadDataFromRequest( $request ) {
374 if ( $request->getCheck( $this->mName
) ) {
375 return $request->getText( $this->mName
);
377 return $this->getDefault();
382 * Initialise the object
384 * @param array $params Associative Array. See HTMLForm doc for syntax.
386 * @since 1.22 The 'label' attribute no longer accepts raw HTML, use 'label-raw' instead
387 * @throws MWException
389 function __construct( $params ) {
390 $this->mParams
= $params;
392 if ( isset( $params['parent'] ) && $params['parent'] instanceof HTMLForm
) {
393 $this->mParent
= $params['parent'];
396 # Generate the label from a message, if possible
397 if ( isset( $params['label-message'] ) ) {
398 $this->mLabel
= $this->getMessage( $params['label-message'] )->parse();
399 } elseif ( isset( $params['label'] ) ) {
400 if ( $params['label'] === ' ' ) {
401 // Apparently some things set   directly and in an odd format
402 $this->mLabel
= ' ';
404 $this->mLabel
= htmlspecialchars( $params['label'] );
406 } elseif ( isset( $params['label-raw'] ) ) {
407 $this->mLabel
= $params['label-raw'];
410 $this->mName
= "wp{$params['fieldname']}";
411 if ( isset( $params['name'] ) ) {
412 $this->mName
= $params['name'];
415 if ( isset( $params['dir'] ) ) {
416 $this->mDir
= $params['dir'];
419 $validName = Sanitizer
::escapeId( $this->mName
);
420 $validName = str_replace( [ '.5B', '.5D' ], [ '[', ']' ], $validName );
421 if ( $this->mName
!= $validName && !isset( $params['nodata'] ) ) {
422 throw new MWException( "Invalid name '{$this->mName}' passed to " . __METHOD__
);
425 $this->mID
= "mw-input-{$this->mName}";
427 if ( isset( $params['default'] ) ) {
428 $this->mDefault
= $params['default'];
431 if ( isset( $params['id'] ) ) {
433 $validId = Sanitizer
::escapeId( $id );
435 if ( $id != $validId ) {
436 throw new MWException( "Invalid id '$id' passed to " . __METHOD__
);
442 if ( isset( $params['cssclass'] ) ) {
443 $this->mClass
= $params['cssclass'];
446 if ( isset( $params['csshelpclass'] ) ) {
447 $this->mHelpClass
= $params['csshelpclass'];
450 if ( isset( $params['validation-callback'] ) ) {
451 $this->mValidationCallback
= $params['validation-callback'];
454 if ( isset( $params['filter-callback'] ) ) {
455 $this->mFilterCallback
= $params['filter-callback'];
458 if ( isset( $params['flatlist'] ) ) {
459 $this->mClass
.= ' mw-htmlform-flatlist';
462 if ( isset( $params['hidelabel'] ) ) {
463 $this->mShowEmptyLabels
= false;
466 if ( isset( $params['hide-if'] ) ) {
467 $this->mHideIf
= $params['hide-if'];
472 * Get the complete table row for the input, including help text,
473 * labels, and whatever.
475 * @param string $value The value to set the input to.
477 * @return string Complete HTML table row.
479 function getTableRow( $value ) {
480 list( $errors, $errorClass ) = $this->getErrorsAndErrorClass( $value );
481 $inputHtml = $this->getInputHTML( $value );
482 $fieldType = get_class( $this );
483 $helptext = $this->getHelpTextHtmlTable( $this->getHelpText() );
484 $cellAttributes = [];
488 if ( !empty( $this->mParams
['vertical-label'] ) ) {
489 $cellAttributes['colspan'] = 2;
490 $verticalLabel = true;
492 $verticalLabel = false;
495 $label = $this->getLabelHtml( $cellAttributes );
497 $field = Html
::rawElement(
499 [ 'class' => 'mw-input' ] +
$cellAttributes,
500 $inputHtml . "\n$errors"
503 if ( $this->mHideIf
) {
504 $rowAttributes['data-hide-if'] = FormatJson
::encode( $this->mHideIf
);
505 $rowClasses .= ' mw-htmlform-hide-if';
508 if ( $verticalLabel ) {
509 $html = Html
::rawElement( 'tr',
510 $rowAttributes +
[ 'class' => "mw-htmlform-vertical-label $rowClasses" ], $label );
511 $html .= Html
::rawElement( 'tr',
513 'class' => "mw-htmlform-field-$fieldType {$this->mClass} $errorClass $rowClasses"
518 Html
::rawElement( 'tr',
520 'class' => "mw-htmlform-field-$fieldType {$this->mClass} $errorClass $rowClasses"
525 return $html . $helptext;
529 * Get the complete div for the input, including help text,
530 * labels, and whatever.
533 * @param string $value The value to set the input to.
535 * @return string Complete HTML table row.
537 public function getDiv( $value ) {
538 list( $errors, $errorClass ) = $this->getErrorsAndErrorClass( $value );
539 $inputHtml = $this->getInputHTML( $value );
540 $fieldType = get_class( $this );
541 $helptext = $this->getHelpTextHtmlDiv( $this->getHelpText() );
542 $cellAttributes = [];
543 $label = $this->getLabelHtml( $cellAttributes );
547 'mw-htmlform-nolabel' => ( $label === '' )
550 $horizontalLabel = isset( $this->mParams
['horizontal-label'] )
551 ?
$this->mParams
['horizontal-label'] : false;
553 if ( $horizontalLabel ) {
554 $field = ' ' . $inputHtml . "\n$errors";
556 $field = Html
::rawElement(
558 [ 'class' => $outerDivClass ] +
$cellAttributes,
559 $inputHtml . "\n$errors"
562 $divCssClasses = [ "mw-htmlform-field-$fieldType",
563 $this->mClass
, $this->mVFormClass
, $errorClass ];
565 $wrapperAttributes = [
566 'class' => $divCssClasses,
568 if ( $this->mHideIf
) {
569 $wrapperAttributes['data-hide-if'] = FormatJson
::encode( $this->mHideIf
);
570 $wrapperAttributes['class'][] = ' mw-htmlform-hide-if';
572 $html = Html
::rawElement( 'div', $wrapperAttributes, $label . $field );
579 * Get the OOUI version of the div. Falls back to getDiv by default.
582 * @param string $value The value to set the input to.
584 * @return OOUI\FieldLayout|OOUI\ActionFieldLayout
586 public function getOOUI( $value ) {
587 $inputField = $this->getInputOOUI( $value );
589 if ( !$inputField ) {
590 // This field doesn't have an OOUI implementation yet at all. Fall back to getDiv() to
591 // generate the whole field, label and errors and all, then wrap it in a Widget.
592 // It might look weird, but it'll work OK.
593 return $this->getFieldLayoutOOUI(
594 new OOUI\
Widget( [ 'content' => new OOUI\
HtmlSnippet( $this->getDiv( $value ) ) ] ),
595 [ 'infusable' => false, 'align' => 'top' ]
600 if ( is_string( $inputField ) ) {
601 // We have an OOUI implementation, but it's not proper, and we got a load of HTML.
602 // Cheat a little and wrap it in a widget. It won't be infusable, though, since client-side
603 // JavaScript doesn't know how to rebuilt the contents.
604 $inputField = new OOUI\
Widget( [ 'content' => new OOUI\
HtmlSnippet( $inputField ) ] );
608 $fieldType = get_class( $this );
609 $helpText = $this->getHelpText();
610 $errors = $this->getErrorsRaw( $value );
611 foreach ( $errors as &$error ) {
612 $error = new OOUI\
HtmlSnippet( $error );
615 $notices = $this->getNotices();
616 foreach ( $notices as &$notice ) {
617 $notice = new OOUI\
HtmlSnippet( $notice );
621 'classes' => [ "mw-htmlform-field-$fieldType", $this->mClass
],
622 'align' => $this->getLabelAlignOOUI(),
623 'help' => $helpText !== null ?
new OOUI\
HtmlSnippet( $helpText ) : null,
625 'notices' => $notices,
626 'infusable' => $infusable,
629 // the element could specify, that the label doesn't need to be added
630 $label = $this->getLabel();
632 $config['label'] = new OOUI\
HtmlSnippet( $label );
635 return $this->getFieldLayoutOOUI( $inputField, $config );
639 * Get label alignment when generating field for OOUI.
640 * @return string 'left', 'right', 'top' or 'inline'
642 protected function getLabelAlignOOUI() {
647 * Get a FieldLayout (or subclass thereof) to wrap this field in when using OOUI output.
648 * @return OOUI\FieldLayout|OOUI\ActionFieldLayout
650 protected function getFieldLayoutOOUI( $inputField, $config ) {
651 if ( isset( $this->mClassWithButton
) ) {
652 $buttonWidget = $this->mClassWithButton
->getInputOOUI( '' );
653 return new OOUI\
ActionFieldLayout( $inputField, $buttonWidget, $config );
655 return new OOUI\
FieldLayout( $inputField, $config );
659 * Get the complete raw fields for the input, including help text,
660 * labels, and whatever.
663 * @param string $value The value to set the input to.
665 * @return string Complete HTML table row.
667 public function getRaw( $value ) {
668 list( $errors, ) = $this->getErrorsAndErrorClass( $value );
669 $inputHtml = $this->getInputHTML( $value );
670 $helptext = $this->getHelpTextHtmlRaw( $this->getHelpText() );
671 $cellAttributes = [];
672 $label = $this->getLabelHtml( $cellAttributes );
683 * Get the complete field for the input, including help text,
684 * labels, and whatever. Fall back from 'vform' to 'div' when not overridden.
687 * @param string $value The value to set the input to.
688 * @return string Complete HTML field.
690 public function getVForm( $value ) {
692 $this->mVFormClass
= ' mw-ui-vform-field';
693 return $this->getDiv( $value );
697 * Get the complete field as an inline element.
699 * @param string $value The value to set the input to.
700 * @return string Complete HTML inline element
702 public function getInline( $value ) {
703 list( $errors, $errorClass ) = $this->getErrorsAndErrorClass( $value );
704 $inputHtml = $this->getInputHTML( $value );
705 $helptext = $this->getHelpTextHtmlDiv( $this->getHelpText() );
706 $cellAttributes = [];
707 $label = $this->getLabelHtml( $cellAttributes );
709 $html = "\n" . $errors .
718 * Generate help text HTML in table format
721 * @param string|null $helptext
724 public function getHelpTextHtmlTable( $helptext ) {
725 if ( is_null( $helptext ) ) {
730 if ( $this->mHideIf
) {
731 $rowAttributes['data-hide-if'] = FormatJson
::encode( $this->mHideIf
);
732 $rowAttributes['class'] = 'mw-htmlform-hide-if';
735 $tdClasses = [ 'htmlform-tip' ];
736 if ( $this->mHelpClass
!== false ) {
737 $tdClasses[] = $this->mHelpClass
;
739 $row = Html
::rawElement( 'td', [ 'colspan' => 2, 'class' => $tdClasses ], $helptext );
740 $row = Html
::rawElement( 'tr', $rowAttributes, $row );
746 * Generate help text HTML in div format
749 * @param string|null $helptext
753 public function getHelpTextHtmlDiv( $helptext ) {
754 if ( is_null( $helptext ) ) {
758 $wrapperAttributes = [
759 'class' => 'htmlform-tip',
761 if ( $this->mHelpClass
!== false ) {
762 $wrapperAttributes['class'] .= " {$this->mHelpClass}";
764 if ( $this->mHideIf
) {
765 $wrapperAttributes['data-hide-if'] = FormatJson
::encode( $this->mHideIf
);
766 $wrapperAttributes['class'] .= ' mw-htmlform-hide-if';
768 $div = Html
::rawElement( 'div', $wrapperAttributes, $helptext );
774 * Generate help text HTML formatted for raw output
777 * @param string|null $helptext
780 public function getHelpTextHtmlRaw( $helptext ) {
781 return $this->getHelpTextHtmlDiv( $helptext );
785 * Determine the help text to display
787 * @return string HTML
789 public function getHelpText() {
792 if ( isset( $this->mParams
['help-message'] ) ) {
793 $this->mParams
['help-messages'] = [ $this->mParams
['help-message'] ];
796 if ( isset( $this->mParams
['help-messages'] ) ) {
797 foreach ( $this->mParams
['help-messages'] as $msg ) {
798 $msg = $this->getMessage( $msg );
800 if ( $msg->exists() ) {
801 if ( is_null( $helptext ) ) {
804 $helptext .= $this->msg( 'word-separator' )->escaped(); // some space
806 $helptext .= $msg->parse(); // Append message
809 } elseif ( isset( $this->mParams
['help'] ) ) {
810 $helptext = $this->mParams
['help'];
817 * Determine form errors to display and their classes
820 * @param string $value The value of the input
821 * @return array array( $errors, $errorClass )
823 public function getErrorsAndErrorClass( $value ) {
824 $errors = $this->validate( $value, $this->mParent
->mFieldData
);
826 if ( is_bool( $errors ) ||
!$this->mParent
->wasSubmitted() ) {
830 $errors = self
::formatErrors( $errors );
831 $errorClass = 'mw-htmlform-invalid-input';
834 return [ $errors, $errorClass ];
838 * Determine form errors to display, returning them in an array.
841 * @param string $value The value of the input
842 * @return string[] Array of error HTML strings
844 public function getErrorsRaw( $value ) {
845 $errors = $this->validate( $value, $this->mParent
->mFieldData
);
847 if ( is_bool( $errors ) ||
!$this->mParent
->wasSubmitted() ) {
851 if ( !is_array( $errors ) ) {
852 $errors = [ $errors ];
854 foreach ( $errors as &$error ) {
855 if ( $error instanceof Message
) {
856 $error = $error->parse();
864 * Determine notices to display for the field.
869 function getNotices() {
872 if ( isset( $this->mParams
['notice-message'] ) ) {
873 $notices[] = $this->getMessage( $this->mParams
['notice-message'] )->parse();
876 if ( isset( $this->mParams
['notice-messages'] ) ) {
877 foreach ( $this->mParams
['notice-messages'] as $msg ) {
878 $notices[] = $this->getMessage( $msg )->parse();
880 } elseif ( isset( $this->mParams
['notice'] ) ) {
881 $notices[] = $this->mParams
['notice'];
888 * @return string HTML
890 function getLabel() {
891 return is_null( $this->mLabel
) ?
'' : $this->mLabel
;
894 function getLabelHtml( $cellAttributes = [] ) {
895 # Don't output a for= attribute for labels with no associated input.
896 # Kind of hacky here, possibly we don't want these to be <label>s at all.
899 if ( $this->needsLabel() ) {
900 $for['for'] = $this->mID
;
903 $labelValue = trim( $this->getLabel() );
905 if ( $labelValue !== ' ' && $labelValue !== '' ) {
909 $displayFormat = $this->mParent
->getDisplayFormat();
911 $horizontalLabel = isset( $this->mParams
['horizontal-label'] )
912 ?
$this->mParams
['horizontal-label'] : false;
914 if ( $displayFormat === 'table' ) {
916 Html
::rawElement( 'td',
917 [ 'class' => 'mw-label' ] +
$cellAttributes,
918 Html
::rawElement( 'label', $for, $labelValue ) );
919 } elseif ( $hasLabel ||
$this->mShowEmptyLabels
) {
920 if ( $displayFormat === 'div' && !$horizontalLabel ) {
922 Html
::rawElement( 'div',
923 [ 'class' => 'mw-label' ] +
$cellAttributes,
924 Html
::rawElement( 'label', $for, $labelValue ) );
926 $html = Html
::rawElement( 'label', $for, $labelValue );
933 function getDefault() {
934 if ( isset( $this->mDefault
) ) {
935 return $this->mDefault
;
942 * Returns the attributes required for the tooltip and accesskey.
944 * @return array Attributes
946 public function getTooltipAndAccessKey() {
947 if ( empty( $this->mParams
['tooltip'] ) ) {
951 return Linker
::tooltipAndAccesskeyAttribs( $this->mParams
['tooltip'] );
955 * Returns the given attributes from the parameters
957 * @param array $list List of attributes to get
958 * @return array Attributes
960 public function getAttributes( array $list ) {
961 static $boolAttribs = [ 'disabled', 'required', 'autofocus', 'multiple', 'readonly' ];
964 foreach ( $list as $key ) {
965 if ( in_array( $key, $boolAttribs ) ) {
966 if ( !empty( $this->mParams
[$key] ) ) {
969 } elseif ( isset( $this->mParams
[$key] ) ) {
970 $ret[$key] = $this->mParams
[$key];
978 * Given an array of msg-key => value mappings, returns an array with keys
979 * being the message texts. It also forces values to strings.
981 * @param array $options
984 private function lookupOptionsKeys( $options ) {
986 foreach ( $options as $key => $value ) {
987 $key = $this->msg( $key )->plain();
988 $ret[$key] = is_array( $value )
989 ?
$this->lookupOptionsKeys( $value )
996 * Recursively forces values in an array to strings, because issues arise
997 * with integer 0 as a value.
999 * @param array $array
1002 static function forceToStringRecursive( $array ) {
1003 if ( is_array( $array ) ) {
1004 return array_map( [ __CLASS__
, 'forceToStringRecursive' ], $array );
1006 return strval( $array );
1011 * Fetch the array of options from the field's parameters. In order, this
1012 * checks 'options-messages', 'options', then 'options-message'.
1014 * @return array|null Options array
1016 public function getOptions() {
1017 if ( $this->mOptions
=== false ) {
1018 if ( array_key_exists( 'options-messages', $this->mParams
) ) {
1019 $this->mOptions
= $this->lookupOptionsKeys( $this->mParams
['options-messages'] );
1020 } elseif ( array_key_exists( 'options', $this->mParams
) ) {
1021 $this->mOptionsLabelsNotFromMessage
= true;
1022 $this->mOptions
= self
::forceToStringRecursive( $this->mParams
['options'] );
1023 } elseif ( array_key_exists( 'options-message', $this->mParams
) ) {
1024 /** @todo This is copied from Xml::listDropDown(), deprecate/avoid duplication? */
1025 $message = $this->getMessage( $this->mParams
['options-message'] )->inContentLanguage()->plain();
1028 $this->mOptions
= [];
1029 foreach ( explode( "\n", $message ) as $option ) {
1030 $value = trim( $option );
1031 if ( $value == '' ) {
1033 } elseif ( substr( $value, 0, 1 ) == '*' && substr( $value, 1, 1 ) != '*' ) {
1034 # A new group is starting...
1035 $value = trim( substr( $value, 1 ) );
1037 } elseif ( substr( $value, 0, 2 ) == '**' ) {
1039 $opt = trim( substr( $value, 2 ) );
1040 if ( $optgroup === false ) {
1041 $this->mOptions
[$opt] = $opt;
1043 $this->mOptions
[$optgroup][$opt] = $opt;
1046 # groupless reason list
1048 $this->mOptions
[$option] = $option;
1052 $this->mOptions
= null;
1056 return $this->mOptions
;
1060 * Get options and make them into arrays suitable for OOUI.
1061 * @return array Options for inclusion in a select or whatever.
1063 public function getOptionsOOUI() {
1064 $oldoptions = $this->getOptions();
1066 if ( $oldoptions === null ) {
1072 foreach ( $oldoptions as $text => $data ) {
1074 'data' => (string)$data,
1075 'label' => (string)$text,
1083 * flatten an array of options to a single array, for instance,
1084 * a set of "<options>" inside "<optgroups>".
1086 * @param array $options Associative Array with values either Strings or Arrays
1087 * @return array Flattened input
1089 public static function flattenOptions( $options ) {
1092 foreach ( $options as $value ) {
1093 if ( is_array( $value ) ) {
1094 $flatOpts = array_merge( $flatOpts, self
::flattenOptions( $value ) );
1096 $flatOpts[] = $value;
1104 * Formats one or more errors as accepted by field validation-callback.
1106 * @param string|Message|array $errors Array of strings or Message instances
1107 * @return string HTML
1110 protected static function formatErrors( $errors ) {
1111 if ( is_array( $errors ) && count( $errors ) === 1 ) {
1112 $errors = array_shift( $errors );
1115 if ( is_array( $errors ) ) {
1117 foreach ( $errors as $error ) {
1118 if ( $error instanceof Message
) {
1119 $lines[] = Html
::rawElement( 'li', [], $error->parse() );
1121 $lines[] = Html
::rawElement( 'li', [], $error );
1125 return Html
::rawElement( 'ul', [ 'class' => 'error' ], implode( "\n", $lines ) );
1127 if ( $errors instanceof Message
) {
1128 $errors = $errors->parse();
1131 return Html
::rawElement( 'span', [ 'class' => 'error' ], $errors );
1136 * Turns a *-message parameter (which could be a MessageSpecifier, or a message name, or a
1137 * name + parameters array) into a Message.
1138 * @param mixed $value
1141 protected function getMessage( $value ) {
1142 $message = Message
::newFromSpecifier( $value );
1144 if ( $this->mParent
) {
1145 $message->setContext( $this->mParent
);
1152 * Skip this field when collecting data.
1153 * @param WebRequest $request
1157 public function skipLoadData( $request ) {
1158 return !empty( $this->mParams
['nodata'] );